package com.hongliang.netty01.eventloop;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @author Hongliang Zhu
 * @create 2021-09-25 10:24
 */
@Slf4j
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException {
        ChannelFuture channelFuture = new Bootstrap()
                // 2. 添加EventLoop
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));

        // 同步处理结果
//        channelFuture.sync(); // 阻塞住当前先后才能，知道nio线程连接建立完毕
//        Channel channel = channelFuture.channel();
//        log.warn("{}", channel);
//        channel.writeAndFlush("hello world");

        // 使用回调对象异步处理结果
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                // nio线程执行
                Channel channel = future.channel();
                // [nioEventLoopGroup-2-1] WARN  c.h.n.e.EventLoopClient -[id: 0x3d72635c, L:/127.0.0.1:11829 - R:localhost/127.0.0.1:8080]
                log.warn("{}", channel);
                channel.writeAndFlush("hello world");
            }
        });
    }
}
